﻿using System.Windows;
using System.Windows.Input;
using System.Windows.Interactivity;

namespace Wen.Core.Behaviors
{
	public class CommandOnClosingBehavior : Behavior<Window>
	{
		public ICommand Command {
			get { return (ICommand)GetValue(CommandProperty); }
			set { SetValue(CommandProperty, value); }
		}
		public static readonly DependencyProperty CommandProperty =
			DependencyProperty.Register("Command", typeof(ICommand), typeof(CommandOnClosingBehavior), new UIPropertyMetadata(null));

		public object CommandParameter {
			get { return GetValue(CommandParameterProperty); }
			set { SetValue(CommandParameterProperty, value); }
		}
		public static readonly DependencyProperty CommandParameterProperty =
			DependencyProperty.Register("CommandParameter", typeof(object), typeof(CommandOnClosingBehavior), new UIPropertyMetadata(null));


		protected override void OnAttached() {
			base.OnAttached();
			AssociatedObject.Closing += AssociatedObjectClosing;
		}

		void AssociatedObjectClosing(object sender, System.ComponentModel.CancelEventArgs e) {
			if (Command != null && Command.CanExecute(CommandParameter))
				Command.Execute(CommandParameter);
		}

		protected override void OnDetaching() {
			base.OnDetaching();
			AssociatedObject.Closing -= AssociatedObjectClosing;
		}
	}
}
